package com.rxt.thermopro.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.app.common.ex.logD
import com.app.common.viewmodel.BaseViewModel
import com.app.common.viewmodel.EventLiveData
import com.orhanobut.hawk.Hawk
import com.rxt.ble.BleManager
import com.rxt.ble.callback.BleWriteCallback
import com.rxt.ble.exception.BleException
import com.rxt.ble.utils.HexUtil
import com.rxt.thermopro.adapter.DeviceListAdapter
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.DeviceBean
import com.rxt.thermopro.bean.EventAlarmData
import com.rxt.thermopro.bean.ProbeBean
import kotlinx.coroutines.*


class DeviceListViewModel : BaseViewModel() {

    val deviceListData: MutableLiveData<MutableList<DeviceBean>> = MutableLiveData()
    val getHistoryTempByCache: EventLiveData<HashMap<String, Long>> = EventLiveData()
    val showAlarmDialog: EventLiveData<HashMap<Long, EventAlarmData>> = EventLiveData()

    val alarmClockDialog1: EventLiveData<HashMap<Long, String>> = EventLiveData()
    val alarmClockDialog2: EventLiveData<HashMap<Long, String>> = EventLiveData()
    val alarmClockDialog3: EventLiveData<HashMap<Long, String>> = EventLiveData()
    val alarmClockDialog4: EventLiveData<HashMap<Long, String>> = EventLiveData()

    val compute2TempTime: EventLiveData<HashMap<String, String>> = EventLiveData()

    val disconnectData: EventLiveData<Pair<String, String>> = EventLiveData()

    val notifyTP960ProbeStatus: EventLiveData<HashMap<String, Pair<Int, String>>> = EventLiveData()


    private var checkWorking = false
    private var checkJob: Job? = null

    fun startCheckTemp(
        block: (isAlarm: Boolean) -> Unit,
        getTempData: () -> HashMap<String, MutableList<ProbeBean>>
    ) {
        checkWorking = true
        checkJob = viewModelScope.launch {
            withContext(Dispatchers.IO) {
                while (checkWorking) {
                    delay(2000)
                    val hashMap = getTempData()
                    var hasTemp100 = false
                    if (hashMap.isNotEmpty()) {
                        hashMap.keys.forEach {
                            val list = hashMap[it] ?: mutableListOf()
                            list.forEach { item ->
                                if (item.temperatureNUm.toIntOrNull() ?: 0 >= 100) {
                                    hasTemp100 = true
                                }
                            }
                        }
                        withContext(Dispatchers.Main) {
                            block(hasTemp100)
                        }
                    }
                }
            }
        }
    }

    private fun stopCheckTemp() {
        checkWorking = false
        checkJob?.cancel()
    }

    override fun onCleared() {
        super.onCleared()
        stopCheckTemp()
    }

    fun initDeviceData() {
        val list = LocalDataDao.INSTANCE.getDeviceList()
        println("123 ->  initDeviceData $list")
        list.forEach {
            if (it.deviceType == DeviceListAdapter.VIEW_TYPE_TP960) {
                it.targetTemp1 = LocalDataDao.INSTANCE.getProfile1(it.address).highTemperatureNum
                it.targetTemp2 = LocalDataDao.INSTANCE.getProfile2(it.address).highTemperatureNum
            }
            //剩余时间格式
            if (it.needTime1!=LocalDataDao.INSTANCE.formatNeedTime()){
                it.needTime1=LocalDataDao.INSTANCE.formatNeedTime()
            }
            if (it.needTime2!=LocalDataDao.INSTANCE.formatNeedTime()){
                it.needTime2=LocalDataDao.INSTANCE.formatNeedTime()
            }
            if (it.needTime3!=LocalDataDao.INSTANCE.formatNeedTime()){
                it.needTime3=LocalDataDao.INSTANCE.formatNeedTime()
            }
            if (it.needTime4!=LocalDataDao.INSTANCE.formatNeedTime()){
                it.needTime4=LocalDataDao.INSTANCE.formatNeedTime()
            }
        }
        deviceListData.value = list
    }

    fun saveDevice(bean: DeviceBean) {
        LocalDataDao.INSTANCE.saveDevice(bean)
    }

    fun removeDevice(item: DeviceBean) {
        LocalDataDao.INSTANCE.removeDevice(item)
    }

    fun removeDevice(address: String) {
        LocalDataDao.INSTANCE.removeDevice(address)
    }

    /**
     * 获取历史数据
     */
    fun getHistoryTemp(address: String, probeIndex: Int) {
        val msg = "020$probeIndex"
        println("getHistoryTemp msg====$msg")
        if (!LocalDataDao.INSTANCE.needGetLastHistory(address)) {
            getHistoryTempByCache.value = hashMapOf<String, Long>().apply {
                this[address] = System.currentTimeMillis()
            }
            return
        }
        LocalDataDao.INSTANCE.setGetHistoryTime(address)
        val deviceList = BleManager.getInstance().allConnectedDevice.filter { it.mac == address }
        if (deviceList.isNotEmpty()) {
            BleManager.getInstance().write(
                deviceList[0],
                TP960ViewModel.BLUETOOTH_SERVICE_UUID_960,
                TP960ViewModel.BLUETOOTH_WRITE_UUID_960,
                HexUtil.hexStringToBytes(msg),
                object : BleWriteCallback() {
                    override fun onWriteSuccess(
                        current: Int,
                        total: Int,
                        justWrite: ByteArray
                    ) {
                        // 发送数据到设备成功
                        logD(" 蓝牙发送数据成功 getHistoryTemp  $msg")

                    }

                    override fun onWriteFailure(exception: BleException) {
                        logD(" 蓝牙发送数据失败  ${exception.toString()}")
                        // 发送数据到设备失败

                    }
                })
        }
    }

}